// utils
import moment from 'moment'
import {
  each,
  isArray,
  isObject,
  isBoolean,
  isString,
  isNumber,
  isDate,
  merge,
  isEmpty as _isEmpty
} from 'lodash'

// let config = {}
// try {
//   if (process.env.NODE_ENV === 'development') {
//     config = require('@/.config.json')
//   }
// } catch (e) {}

// 把一个object数据清空
export const empty = obj => {
  let o = {}
  each(obj, (r, k) => {
    if (isObject(r)) {
      o[k] = isArray(r) ? [] : {}
    } else {
      if (r !== '') {
        o[k] = r
      }
    }
  })
  return o
}

// 把一个object数据结构深度清空
export const emptyDeep = obj => {
  let o = {}
  each(obj, (item, key) => {
    if (item !== null) {
      if (isArray(item)) {
        o[key] = []
      } else {
        if (isObject(item)) {
          o[key] = emptyDeep(item)
        } else {
          o[key] = ''
        }
      }
    }
  })
  return o
}
/**
 * true/是，false
 */
export const isChangeBoolen = value => {
  return value ? '是' : '否'
}
// 手机打码
export const maskmobile = mobile => {
  if (!mobile) return
  return mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 身份证打码
export const maskIdNumber = id => {
  return id.replace(/^(.{3})(.*)(.{4})$/, '$1********$3')
}

// 姓名打码
export const maskName = name => {
  if (name.length < 2) {
    return
  }
  let arr = name.split('')
  if (arr.length === 2) {
    return arr[0] + '*'
  } else {
    return arr[0] + '*' + (arr[arr.length - 1])
  }
}

// 阿拉伯数字转中文数字
export const num2str = num => {
  let map = {
    0: '零',
    1: '一',
    2: '二',
    3: '三',
    4: '四',
    5: '五',
    6: '六',
    7: '七',
    8: '八',
    9: '九',
    10: '十'
  }
  return map[num.toString()]
}

// 处理图片返回地址
// export const img = url => {
//   let replace = '/'
//   if (process.env.NODE_ENV === 'development') {
//     let target = get(config, 'dev.proxyTable./api.target', null)
//     if (target) {
//       replace = target.replace('/api', '/')
//     }
//   }
//   return url.replace('file/', replace)
// }

// 获取滚动条距离顶部距离
export const getScrollTop = () => {
  let scrollPos = null
  if (window.pageYOffset) {
    scrollPos = window.pageYOffset
  } else if (document.compatMode && document.compatMode !== 'BackCompat') {
    scrollPos = document.documentElement.scrollTop
  } else if (document.body) {
    scrollPos = document.body.scrollTop
  }
  return scrollPos
}

// debounce function
let runtime = window.__nb_runtime || 0
let timer = window.__nb_timer
export const debounce = (func, timerOffset = 200) => {
  let now = Date.now()
  if (runtime > 0 && now - runtime < timerOffset) {
    timer && clearTimeout(timer)
    window.__nb_runtime = 0
    window.__nb_timer = null
  }
  runtime = now
  timer = setTimeout(() => {
    func.call()
  }, timerOffset)
}

export const s4 = () => {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
export const uuid = () => {
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4()
}

// isEmpty
export const isEmpty = (val) => {
  if (val === null || val === undefined || val === '') {
    return true
  }
  if (isBoolean(val)) return false
  if (isString(val)) return false
  if (isNumber(val)) return false
  if (isDate(val)) return false
  return _isEmpty(val)
}

export const toHref = url => {
  if (isEmpty(url)) return null
  if (url.indexOf('http://') > -1 || url.indexOf('https://') > -1) {
    return url
  } else {
    return `//${url}`
  }
}

// 将数组拼接成key,value形式
export const getNewArray = (key, arr) => {
  if (isEmpty(arr)) return null
  return arr.join(`&${key}=`)
}

// currentcy format
export const currency = (value, prefix) => {
  if (!value) return null
  let curry = {
    CNY: '￥',
    USD: '$'
  }[prefix] || ''
  if (value >= 100000000) {
    return `${curry}${value / 100000000}亿`
  } else {
    return `${curry}${value / 10000}万`
  }
}

/**
 * 校验手机号
 */
export const isPhone = phone => {
  return /^1[0-9]{10}$/.test(phone)
}
/**
 * 只能输入0 或非零开头的数字
 */
export const isInteger = value => {
  return /^(0|[1-9][0-9]*)$/.test(value)
}
/**
 * 校验金额
 */
export const isMoney = value => {
  return /(^[1-9]([0-9]+)?(\.[0-9]{1,4})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value)
}
/**
 * 校验密码
 */
export const isPassword = value => {
  return /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,18}$/.test(value)
}
/**
 * 验证小数2位或4位
 */
export const isDecimal = value => {
  return /^\d{0,8}\.{0,1}((\d{2})|(\d{4}))?$/.test(value)
}
/**
 * 验证小数4位
 */
export const isDecimalFour = value => {
  return /^\d{0,8}\.{0,1}(\d{0,4})?$/.test(value)
}
/**
 * 验证小数2位
 */
export const isDouDecimal = value => {
  return /^(\d|[1-9]\d|100)(\.\d{1,2})?$/.test(value)
}
/**
 * 格式化时间
 */
export const formatDate = (value, pattern) => {
  pattern = pattern || 'YYYY-MM-DD HH:mm'
  if (!value || value === '') return ''
  return moment(value).format(pattern)
}
/**
 * 格式化范围
 */
export const formatScope = value => {
  if (!value.length) return ''
  return value
}

/**
 * table表格内数据过滤
 */
export const formatTable = {
  phone: (() => {
    return maskmobile
  })(),
  card: (() => {
    return maskIdNumber
  })(),
  date: (() => {
    return formatDate
  })(),
  boolen: (() => {
    return isChangeBoolen
  })()
}

/**
 * nb-form 数据过滤
 */
export const formatInput = {
  date: (() => {
    return formatDate
  })(),
  scope: (() => {
    return formatScope
  })()
}
/**
 * 获取url数据
 */
export const getUrlParam = name => {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') // 构造一个含有目标参数的正则表达式对象
  let r = window.location.search.substr(1).match(reg) // 匹配目标参数
  if (r !== null) return unescape(r[2])
  return null // 返回参数值
}
/**
 * 合并表头
 */
export const mergeHeader = (header, data) => {
  header.map(item => {
    data.map(items => {
      if (item.headerKey === items.headerKey) {
        merge(item, items)
      }
    })
  })
}

/**
 * 证件号 只能输入数字或字母
 */
export const checkCard = value => {
  return /^[a-zA-Z\d]+$/.test(value)
}
/**
 * 证件号 只能输入数字或字母或括号 香港身份证校验
 */
export const checkCard3 = value => {
  return /[A-Z][0-9]{6}\([0-9A]\)/.test(value)
}
/**
 * 证件号 只能输入数字或字母或括号 台湾身份证校验
 */
export const checkCardTW = value => {
  return /[A-Z][0-9]{9}/.test(value)
}
/**
 * 证件号 只能输入数字或字母或汉字
 */
export const checkCard2 = value => {
  return /^[a-zA-Z\d\u4e00-\u9fa5]+$/.test(value)
}
/**
 * 获取元素距离顶部左部边框的距离
 */
export const getAbsPoint = (e) => {
  let x = 0
  let y = 0
  add(e)
  function add (e) {
    x += e.offsetLeft
    y += e.offsetTop
    if (e.offsetParent) {
      e = e.offsetParent
      add(e)
    }
  }
  return {'x': x, 'y': y}
}
/**
*验证 0-99 之间的整数
*/
export const isNine = value => {
  return /^([1-9]\d|\d)$/.test(value)
}
/**
*验证 1-99 之间的整数
*/
export const isFtoN = value => {
  return /^([1-9]\d?|99)$/.test(value)
}
/**
*验证 1-999之间的整数
*/
export const isFtoHn = value => {
  return /^[1-9][0-9]{0,2}$/.test(value)
}
/**
*验证 https://或者https://开头
*/
export const urlHeader = value => {
  return /^[1-9][0-9]{0,2}$/.test(value)
}
/**
 * 获取目标字段数组
 */
export const fieldArr = (target, key = 'id') => {
  let arr = []
  if (target) {
    target.map(item => {
      arr.push(item[key])
    })
  }
  return arr
}
/**
 * 提取代码段文字
 */
export const htmlContent = value => {
  let msg = value.replace(('<.+?>', 'g'), '')
  return msg
}
/**
 * 处理formData表单提交 时有对象的情况，
 * 将对象拆分成如下 visibleScope.name + value
 * 对象名需要传递进来
 */
export const formDataObject = (object, target, data) => {
  for (let key in data) {
    if (Object.prototype.toString.call(data[key]) === '[object Array]' && data[key].length) {
      data[key].map(item => {
        target.append(`${object}.${key}`, item)
      })
    } else {
      target.append(`${object}.${key}`, data[key])
    }
  }
}

/**
 * 处理checkbox 数据
 */
export const handleScope = (value) => {
  if (!value) return []
  let m = '000000000000000000'
  let t = value.toString(2).split('').reverse()
  let target = []
  t.map((item, index) => {
    if (item === '1') {
      target.push(parseInt(`1${m.substring(0, index)}`, 2))
    }
  })
  return target || []
}
/**
 * 正整数
 */
export const isPositiveInteger = value => {
  return /^(0|[1-9][0-9]*)$/.test(value)
}
/**
 * 非0正整数
 */
export const isEcpInteger = value => {
  return /^\+?[1-9][0-9]*$/.test(value)
}
/**
* 最多四位小数
*/
export const isFourDecimal = value => {
  return /^([1-9]\d{0,200}|0)(\.\d{1,4})?$/.test(value)
}
/**
* 1-9999
*/
export const isToFn = value => {
  return /^[1-9][0-9]{0,3}$/.test(value)
}
/**
* 1-30正整数
*/
export const isToTh = value => {
  return /^([12][0-9]|30|[1-9])$/.test(value)
}
/**
* 正数，且最多保留两位小数
*/
export const isTwDec = value => {
  return /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(value)
}
/**
* 0-100(不包含0)，且最多保留两位小数
*/
export const isTwHun = value => {
  return /^\d\.([1-9]{1,2}|[0-9][1-9])$|^[1-9]\d{0,1}(\.\d{1,2}){0,1}$|^100(\.0{1,2}){0,1}$/.test(value)
}
/**
 * 接口数据编码
 */

export const setCookie = function (cname, cvalue, exdays) {
  function GetCookieDomain () {
    let host = location.hostname
    let ip = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
    if (ip.test(host) === true || host === 'localhost') return host
    let regex = /([^]*).*/
    let match = host.match(regex)
    if (typeof match !== 'undefined' && match !== null) host = match[1]
    if (typeof host !== 'undefined' && host !== null) {
      let strAry = host.split('.')
      if (strAry.length > 1) {
        host = strAry[strAry.length - 2] + '.' + strAry[strAry.length - 1]
      }
    }
    return '.' + host
  }
  let d = new Date()
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000))
  let expires = 'expires=' + d.toUTCString()
  document.cookie = cname + '=' + cvalue + '; ' + expires + ';domain=' + GetCookieDomain() + ';path=/'
}
/**
 * 清空搜索条件
 */
export const empModel = (obj, field = []) => {
  obj.orderBy = ''
  for (let i in obj.param) {
    if (field.indexOf(i) === -1) {
      obj.param[i] = ''
    }
  }
}
/**
 * promise 接口api处理
 */
export const promiseApi = (
  Vue,
  url,
  data,
  headers,
  options,
  method = 'post'
) => {
  headers = headers || {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }
  if (options) {
    merge(headers, options)
  }
  return new Promise((resolve, reject) => {
    Vue.req[method](url, data, headers)
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}
/**
 * 移除参数中的空值
*/
export function removeEmptyParams (params = {}) {
  let copyParams = params
  Object.keys(copyParams).forEach(key => {
    let val = copyParams[key]
    if (val === '' || val === undefined || val === null) {
      delete copyParams[key]
    }
  })
  return copyParams
}
/**
 * 下拉中获取name
*/
export function getSelectName (currentValue, keyValue, allSelectList) {
  let currentName = ''
  let tempList = allSelectList
  tempList.map((v, i) => {
    if (v[keyValue.valueCode] === currentValue) {
      currentName = v[keyValue.valueName]
    }
  })
  return currentName
}
